<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <!-- 旧件出库新增 - 车厂 - 编辑页面 -->
      <BreakSpace label="旧件出库·" :containerStyle="{ marginBottom: '10px' }" />
      <FormPanel ref="formPanel1" :list="formList" :cols="3" :formType="'add'" labelWidth="70" :isSubmitBtn="false"
        @formChange="formChangeHandle" />

      <BreakSpace label="旧件列表" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable ref="table" :columns="columns" :params="fetchParams" :dataSource="dataList" :datakey="'items'"
        :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChange" selectionType="single"
        height="auto" :isPagination=false :isSelectColumn=false>
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">添加</multiuse-button>
        </template>
      </FilterTable>
     <!-- 旧件库存选择1 -->
     <BaseDialog :visible.sync="jiujianFlag" :title="'旧件选择'" destroyOnClose width="850px"
        :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <selectjiujian @close="jiujianclose" @save="saveMaintainItemSelect"  :rowData="dataTypeValue" :rowType="PartType" :dataList = 'dataList' ></selectjiujian>
      </BaseDialog>
      <!-- 旧件库存选择1 -->
      <BaseDialog :visible.sync="jiujianFlag1" :title="'旧件选择'" destroyOnClose width="850px"
        :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <selectjiujianOther @close="jiujianclose1" @save="saveMaintainItemSelect" :rowData="dataTypeValue"  :rowType="PartType" :dataList = 'dataList' ></selectjiujianOther>
      </BaseDialog>
      <!--   <BaseDialog :visible.sync="suppliers" :title="'供应商选择'" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <SupplierList @close="suppliersClose" @save="suppliersSave"></SupplierList>
    </BaseDialog> -->
      <div style="margin-bottom: 1rem;"></div>
      <div style="padding-top: 3rem;"></div>
      <div :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }">
        <!--      <multiuse-button type="primary" @click="">打 印</multiuse-button>-->
        <multiuse-button type="primary" size="small" :click="saveDialog.bind()">保 存</multiuse-button>
        <multiuse-button type="primary" size="small" :click="saveDialog2.bind()">出 库</multiuse-button>
        <multiuse-button size="small" @click="closeDialog">关 闭</multiuse-button>
      </div>
    </div>
  </Spin>
</template>
<script>
// import res from '@/mock/tableData';
//手机号校验
import { phone } from '@/utils/validate';
//日期、时间控件默认值设置
import moment from 'moment';
import selectjiujian from './selectjiujian.vue';
import selectjiujianOther from './selectjiujianOther';
//公共方法editSave
import { getPartType, getSupplierList } from '@/api/dictionary/index.js';
import { editSave, selectEditById } from '@/api/usedPartsReturnManage/usedPartsReturn_OEM/usedPartsOutOfStock';
import { dictionary } from '@/utils/dictMixin';
//供应商
//import SupplierList from '@/pages/claimDemage/tools/SuppliersList.vue';

export default {
  props: ['rowData'],
  mixins: [dictionary],
  components: {
    selectjiujian,
    selectjiujianOther

    //SupplierList
  },
  data() {
    return {
      loading: false,
      editData: [],
      delList:'',
      editDatas: {},
      dataList: [],
      visible: false,
      visibleDrawer: false,
      collapse: false,
      jiujianFlag: false,
      PartType:null,
      jiujianFlag1: false,
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中服务站
      formList: this.createFormList(),
      saveData: null,
      deleId: [],
      suppliers: false,
      supId: null,
      supName: null,
      supCode: null,
      dataTypeValue: null,
    };
  },
  async created() {
    //this.loading = true;
    await this.chuqi2();
    await this.init(this.rowData.outId);
    this.loading = false;
  },
  methods: {
    //出库类型下拉框
    async chuqi2() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 5523 });
      console.log("==========", res)
      if (res.resultCode == 200) {
        this.formList.find(x => x.fieldName == 'outType').initialValue = '';
        this.formList.find(x => x.fieldName == 'outType').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    async init(val) {
      let newVar = await selectEditById({ outId: val });
      this.editData = newVar.data.dtlList;
      console.log("=== 通过ID查询结果返回 editData ==== ", this.editData, " ======");
      console.log("=== 通过ID查询结果返回 ==== ", newVar, " ======");
      this.formList.forEach(x => {
        console.log(newVar);
        if(x.fieldName == 'outStatus' && newVar.data['outStatus']) {
          x.initialValue = Number(newVar.data['outStatus']);
          //x.initialValue =newVar.data['outStatus'];
          // 更新列表中的库存类型
          newVar.data.dtlList.forEach(item => {
            item.outStatus = String(newVar.data['outStatus']);
            item.partStatus = String(newVar.data['outStatus']);
          });
        } else {
          x.initialValue = newVar.data[x.fieldName];
          this.supCode = newVar.data['supCode']
        }
      });
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(newVar.data.dtlList);
    },
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },
    /* suppliersClose(){
      this.suppliers = false;
    },
    suppliersSave(obj) {
      this.formList.find(x => x.fieldName == 'supName').initialValue = obj[0].supName;
      this.supCode = obj[0].supCode;
      this.supId = obj[0].supId;
      this.suppliers = false;
    },
    selectSuppliersCode() {
      this.suppliers = true;
    }, */
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
      console.log(val);
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    //服务站选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //删除
    deleteHandle(row) {
      console.log("row" + JSON.stringify(row));
      // this.pushDeleteIds(row);
      console.log("row" + JSON.stringify(row.dtlId));
      if(row.dtlId!=null&&row.dtlId!=''&&row.dtlId!="undefined"){
        this.delList = row.dtlId+","+this.delList

      }

      console.log("row" + this.delList);

      this.$refs.table.$refs.pageTable.EXECUTE_DELETE([row]);
    },
    //保存
    async saveDialog() {
      let err = this.$refs.formPanel1.submitForm();
      if (err) {
        // this.$notify.error({ title: '提示信息', message: '请检查提交数据' });
        return;
      }
      console.log(this.saveData);
      console.log(this.dataList);
      if (!this.dataList || this.dataList.length == 0) {
        this.$notify.error({ title: '提示信息', message: '旧件列表不能为空' });
        return;
      }

      let bool = false;

      this.dataList.forEach(x => {
        if (bool) {
          return;
        }

        if (x.stockCount < x.outCount) {
          this.$notify.error({ title: '提示信息', message: '出库数量不能大于库存数量' });
          bool = true;
          return;
        }
        if (x.outCount <= 0 || x.outCount === null) {
          this.$notify.error({ title: '提示信息', message: '请输入正确的出库数量' });
          bool = true;
          return;
        }
        x.outCount = Number(x.outCount)
        x.partCount = x.stockCount
      })
      if (bool) {
        return;
      }
      console.log("11111",this.delList)
      if(this.delList!=null&&this.delList!=''&&this.delList!='undefined'){
        var index=this.delList.lastIndexOf(",")
        this.delList=this.delList.substring(0,index)
      }

      console.log("22222",this.delList)
      let save = Object.assign({}, this.saveData, { dtlList: this.dataList },
       {outId:this.rowData.outId},
        { isOutPart: 30151001 },
          {supCode: this.supCode },
        // { supName: this.supName },
        {delDtlIds:this.delList},
        { outStatus:Number(this.formList.find(x => x.fieldName == 'outStatus').initialValue) }

      );
      //this.loading = true;
      let res = await editSave(save);
      if (res.resultCode === 200) {
        this.loading = false;
        this.$notify.success({ title: '提示信息', message: '保存成功!' });
        this.$emit('save');
      } else {
        this.loading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });

      }
    },

    //出库
    async saveDialog2() {
      let err = this.$refs.formPanel1.submitForm();
      if (err) {
        // this.$notify.error({ title: '提示信息', message: '请检查提交数据' });
        return;
      }
      console.log('1111',this.saveData);
      console.log('122222',this.dataList);
      if (!this.dataList || this.dataList.length == 0) {
        this.$notify.error({ title: '提示信息', message: '旧件列表不能为空' });
        return;
      }

      let bool = false;
      this.dataList.forEach(x => {
        if (bool) {
          return;
        }
        if(x.stockCount ==0){
          this.$notify.error({ title: '提示信息', message: '请删除库存数量为0的数据' });
          bool = true;
          return;
        }

        if (x.stockCount < x.outCount) {
          this.$notify.error({ title: '提示信息', message: '出库数量不能大于库存数量' });
          bool = true;
          return;
        }
        if (x.outCount <= 0 || x.outCount === null) {
          this.$notify.error({ title: '提示信息', message: '请输入正确的出库数量' });
          bool = true;
          return;
        }
        x.outCount = Number(x.outCount)
        x.partCount = x.stockCount
      })
      if (bool) {
        return;
      }
      if(this.delList!=null&&this.delList!=''&&this.delList!='undefined'){
        var index=this.delList.lastIndexOf(",")
        this.delList=this.delList.substring(0,index)
      }
      let save = Object.assign({}, this.saveData, { dtlList: this.dataList },
         {outId:this.rowData.outId},
        { isOutPart: 30151003 },
        { supCode: this.supCode },
        {delDtlIds:this.delList},
        { outStatus:Number(this.formList.find(x => x.fieldName == 'outStatus').initialValue) }

      );
      //this.loading = true;
      let res = await editSave(save);
      if (res.resultCode === 200) {
        this.loading = false;
        this.$notify.success({ title: '提示信息', message: '出库成功!' });
        this.$emit('save');
      } else {
        this.loading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '出库失败!' });
      }
    },

    //子页面带回数据
    saveMaintainItemSelect(val) {
      console.log(val);
      this.editData = val;
      this.jiujianFlag = false;
      this.jiujianFlag1 = false;
      let list = [];
      this.dataList = [...this.dataList,...val];
      // let pageList = this.$refs.table.$refs.pageTable.list;
      // val.map(x => {
      //   if (pageList.length == 0) {
      //     console.log("没有值，直接添加")

      //     pageList.push(x);
      //   } else {
      //     console.log("pageList",pageList)
      //     console.log("val",val)
      //     /* if (!pageList.find(f => f.hisId == x.hisId)) {
      //       console.log("11111")
      //       pageList.push(x);
      //     } */
      //     if (pageList.find(f => f.partCode == x.partCode)) {
      //       this.$notify.error({ title: '提示信息', message: '请选择不同的旧件代码进行添加' });
      //     }
      //       else{
      //         console.log("11111")
      //         pageList.push(x);
      //       }
      //   }
      // });
      // console.log("=====", list)
      // // this.$refs.table.$refs.pageTable.EXECUTE_DELETE(this.$refs.table.$refs.pageTable.list);
      // //this.$refs.table.$refs.pageTable.EXECUTE_INSERT(pageList);
      // this.fetchParams = { ...this.fetchParams };
    },
    chooseOrderNo() {
      this.visible = true;
    },
    add() {
      if (this.formList.find(x => x.fieldName == 'outType').initialValue === 55231001) {// 服务中心
        this.jiujianFlag = true;
        this.PartType =this.formList.find(x => x.fieldName == 'outStatus').initialValue
        this.dataTypeValue = this.formList.find(x => x.fieldName == 'supName').initialValue
      } else {// 供应商，报废，其他
        this.jiujianFlag1 = true;
        this.PartType =this.formList.find(x => x.fieldName == 'outStatus').initialValue
        this.dataTypeValue = this.formList.find(x => x.fieldName == 'supName').initialValue
      }
    },
    jiujianclose() {
      this.jiujianFlag = false;
    },
    jiujianclose1() {
      this.jiujianFlag1 = false;
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '出库单号',
          fieldName: 'outNo',
          readonly: true,// 只读
          disabled: true // 置灰
        },
        {
          type: 'SELECT',
          label: '出库类型',
          fieldName: 'outType',
          placeholder: '请选择出库类型...',
          itemList: this.createDictList('5523'),
          rules: [{ required: true, message: '请选择出库类型...', trigger: 'change' }],
          readonly: true, // 只读
          disabled: true ,// 置灰
        },
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'supName',
          placeholder: '请选择供应商...',
          readonly: true,// 只读
          disabled: true // 置灰
          // hidden:false,
          //rules: [{ required: true, message: '请选择供应商...', trigger: 'blur', }],
        /*   unitRender: p => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.selectSuppliersCode()} />
              </div>
            );
          } */
        },
        {
          type: 'SELECT',
          label: '库存类型',
          fieldName: 'outStatus',
          placeholder: '请选择库存类型...',
          initialValue: '',
          disabled: true,
          itemList: [{ text: '合格库', value: 1 }, { text: '不合格库', value: 0 }],
          rules: [{ required: true, message: '请选择库存类型', trigger: ['blur','change'] }],
        },
        {
          type: 'DATE',
          label: '出库日期',
          fieldName: 'outDate',
          // placeholder: '选择日期...',
          // initialValue: moment(new Date()).format('YYYY-MM-DD'),
          disabled: true // 置灰
          // rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        /*  {
           type: 'INPUT',
           label: '供应商',
           fieldName: 'supName',
           placeholder: '请选择供应商...',
           readonly: true,// 只读
           rules: [{required: false, message: '请选择供应商...', trigger: 'blur'}],
           unitRender: p => {
             return (
               <div>
                 <multiuse-button icon="el-icon-search" onClick={() => this.selectSuppliersCode()} />
               </div>
             );
           }
         }, */
        /*  {
           type: 'INPUT',
           label: '领件人',
           placeholder: '请输入领件人...',
           fieldName: 'outTo',
           rules: [{required: true, message: '请输入领件人...', trigger: 'change'}],
         },
         {
           type: 'INPUT',
           label: '联系电话',
           fieldName: 'outPhone',
           placeholder: '请输入联系电话...',
           rules: [{required: true, message: '请输入联系电话...', trigger: 'change'}, {pattern: /^1[2-9]\d{9}$/, message: '请检查联系电话格式...', trigger: 'blur',}],
         }, */
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'outRemarks',
          disabled: true, // 置灰
          placeholder: '请输入备注...',
          selfCols: 3,// 元素占据几行
          rows: 3
        }
      ];
    },

    //旧件列表
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: (props) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.deleteHandle(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          },
        },

       /*  {title: '索赔单号', dataIndex: 'cmsClaimNo', sorter: true}, */
        {title: '旧件代码', dataIndex: 'partCode', sorter: true},
        {title: '旧件名称', dataIndex: 'partName', sorter: true},
        {title: '库存类型', dataIndex: 'outStatus', sorter: true,  dictItems: [{ text: '合格库', value: 1 },{ text: '不合格库', value: 0 }],},
        {title: '库存数量', dataIndex: 'stockCount', sorter: true},
          {title: '出库数量',
          dataIndex: 'outCount',
          sorter: true,
          minWidth: 120,
          editable: true,
          defaultEditable: true,
          showOverflowTooltip: true,
          precision: 0,
          editType: 'number',
          editRequired: true,
          rules: [{ required: true, message: '请填写出库数量', trigger: 'blur' }]
        },
      ];
    }
  }
};
</script>
<style lang="less" scoped>

</style>
